<script setup>
import { ref, reactive, watchEffect } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  // 编辑模式时传入的大题数据
  bigQuestion: {
    type: Object,
    default: () => ({})
  },
  // 学科ID
  subjectId: {
    type: Number,
    required: true
  },
  // 是否为编辑模式
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['success', 'cancel'])

// 表单数据
const formData = reactive({
  id: props.bigQuestion?.id || undefined,
  name: props.bigQuestion?.name || '',
  subjectId: props.subjectId
})

// 监听props变化，更新表单数据
watchEffect(() => {
  if (props.isEdit && props.bigQuestion) {
    formData.id = props.bigQuestion.id
    formData.name = props.bigQuestion.name
    formData.subjectId = props.bigQuestion.subjectId || props.subjectId
  }
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入大题名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  subjectId: [
    { required: true, message: '学科ID不能为空', trigger: 'change' }
  ]
}

// 表单引用
const formRef = ref(null)

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      emit('success', { ...formData })
    } else {
      ElMessage.warning('请完善表单信息')
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 取消操作
const handleCancel = () => {
  resetForm()
  emit('cancel')
}

// 对外暴露方法
defineExpose({
  resetForm
})
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="100px"
    class="big-question-form"
  >
    <el-form-item label="大题名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入大题名称" />
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.big-question-form {
  max-width: 600px;
  margin: 0 auto;
}
</style>